<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { usePhotoStore } from '../stores/photo'
import { getPhotoList, deletePhoto } from '../api/photo'
import { showToast, showDialog, showConfirmDialog } from 'vant'

const router = useRouter()
const photoStore = usePhotoStore()
const loading = ref(false)
const isRequesting = ref(false)
const photoListDom = ref(null)

const fetchPhotoList = async (url, isLoadMore = false) => {
  try {
    if (!isLoadMore) {
      loading.value = true
    }
    isRequesting.value = true
    const response = await getPhotoList(url, photoStore.page)
    
    if (isLoadMore) {
      photoStore.appendPhotoList(response)
    } else {
      photoStore.setPhotoList(response)
    }
    
    // 判断是否还有更多数据
    photoStore.hasMore = response && response.length > 0
  } catch (error) {
    showToast('获取照片列表失败')
  } finally {
    loading.value = false
    isRequesting.value = false
  }
}

// 监听滚动事件
const handleScroll = async (e) => {
  const element = e.target
  if (element.scrollHeight - element.scrollTop - element.clientHeight < 50) {
    if (!loading.value && !isRequesting.value && photoStore.hasMore) {
      const url = router.currentRoute.value.query.url || ''
      photoStore.setPage(photoStore.page + 1)
      await fetchPhotoList(url, true)
    }
  }
}

// 监听路由参数变化
watch(
  () => router.currentRoute.value.query.url,
  (newUrl) => {
    photoStore.reset()
    fetchPhotoList(newUrl || '')
  }
)

const handleItemClick = (item) => {
  if (delMode.value) {
    return addDelItem(item)
  }
  if (item.isDirectory) {
    router.push({
      name: 'PhotoList',
      query: { url: item.url }
    })
  } else if (item.isPic) {
    photoStore.setCurrentPhoto(item)
    router.push({
      name: 'PhotoView',
      params: { url: item.url }
    })
  } else if (item.isVideo || item.isAudio) {
    window.open(item.url)
  } else {
    const formatFileSize = (bytes) => {
      if (!bytes) return '0 MB'
      return (bytes / (1024 * 1024)).toFixed(2) + ' MB'
    }
    const formatDateTime = (isoString) => {
      if (!isoString) return '-'
      return isoString.replace('T', ' ').split('.')[0]
    }
    showDialog({
      message: `
        <div class="info-dialog">
          <div><h4>${item.name}</h4></div>
          <div><span>大小：</span><span>${formatFileSize(item.size)}</span></div>
          <div><span>时间：</span><span>${formatDateTime(item.createTime)}</span></div>
          <div><span>路径：</span><span>${item.url}</span></div>
          <br><hr><br>
          <a href="javascript:window.open('${item.url}')">下载</a>
        </div>
      `,
      messageAlign: 'center',
      zIndex: 110000,
      closeOnClickOverlay: true,
      showConfirmButton: false,
      allowHtml: true
    })
  }
}

onMounted(() => {
  const url = router.currentRoute.value.query.url || ''
  if (!photoStore.currentPhoto) {
    fetchPhotoList(url)
  } else {
    const index = photoStore.currentIndex
    const rowHeight = (photoListDom.value.clientWidth - 50) / 4
    const scrollTop = (index - 12) * rowHeight / 4
    photoListDom.value.scrollTop = scrollTop
  }
})
const delMode = ref(false)
const changeDelMode = async () => {
  delMode.value = !delMode.value
  if (delMode.value) {
    showToast('进入删除模式')
  } else {
    if (delItems.value.length > 0) {
      try {
        await showConfirmDialog({
          title: '不可恢复',
          message: `确定要删除选中的${delItems.value.length}个文件吗？`,
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          zIndex: 110000,
        })
        const res = await deletePhoto(delItems.value)
        if (res.success) {
          showToast('删除成功')
          photoStore.removePhotos(delItems.value)
          delItems.value = []
        } else {
          showToast('删除失败')
        }
      } catch (error) {
        showToast('退出删除模式')
        delItems.value = []
        return
      }
    } else {
      showToast('退出删除模式')
    }
  }
}
const delItems = ref([])
const addDelItem = (item) => {
  if (delItems.value.includes(item.url)) {
    delItems.value = delItems.value.filter(i => i !== item.url)
  } else {
    delItems.value.push(item.url)
  }
}
</script>

<template>
  <div class="photo-list" ref="photoListDom" @scroll="handleScroll">
    <van-loading v-if="loading" size="50" vertical>加载中....</van-loading>
    <div v-else class="flex-container">
      <div 
        v-for="item in photoStore.photoList" 
        :key="item.url" 
        :class="`flex-item ${delItems.includes(item.url) ? 'need-del' : ''}`"
        @click="handleItemClick(item)"
      >
        <template v-if="item.isDirectory">
          <div class="item-box">
            <svg t="1745982797811" class="folder-icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3660" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M853.333333 938.666667 42.666667 938.666667c-25.6 0-42.666667-17.066667-42.666667-42.666667L0 128c0-25.6 17.066667-42.666667 42.666667-42.666667l298.666667 0c25.6 0 42.666667 17.066667 42.666667 42.666667l0 42.666667 469.333333 0c25.6 0 42.666667 17.066667 42.666667 42.666667l0 170.666667c0 25.6-17.066667 42.666667-42.666667 42.666667s-42.666667-17.066667-42.666667-42.666667L810.666667 256 341.333333 256C315.733333 256 298.666667 238.933333 298.666667 213.333333L298.666667 170.666667 85.333333 170.666667l0 682.666667 768 0c25.6 0 42.666667 17.066667 42.666667 42.666667S878.933333 938.666667 853.333333 938.666667z" p-id="3661"></path><path d="M853.333333 938.666667 42.666667 938.666667c-12.8 0-25.6-4.266667-34.133333-17.066667S0 900.266667 0 887.466667l128-512C132.266667 354.133333 149.333333 341.333333 170.666667 341.333333l810.666667 0c12.8 0 25.6 4.266667 34.133333 17.066667S1024 379.733333 1024 392.533333l-128 512C891.733333 925.866667 874.666667 938.666667 853.333333 938.666667zM98.133333 853.333333l721.066667 0 106.666667-426.666667L204.8 426.666667 98.133333 853.333333z" p-id="3662"></path></svg>
            <span>{{ item.name }}</span>
          </div>
        </template>
        <template v-if="item.isPic">
          <img :src="item.thumbnailUrl">
        </template>
        <template v-if="item.isVideo">
          <div class="item-box">
            <svg class="video-icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3660" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M896 128H128c-35.2 0-64 28.8-64 64v640c0 35.2 28.8 64 64 64h768c35.2 0 64-28.8 64-64V192c0-35.2-28.8-64-64-64zM384 704V320l384 192-384 192z" p-id="3661"></path></svg>
            <span>{{ item.name }}</span>
          </div>
        </template>
        <template v-else>
          <div class="item-box"><span>{{ item.name }}</span></div>
        </template>
      </div>
    </div>
    <div :class="`del-btn ${delMode}`" @click="changeDelMode">
      <svg t="1745908716501" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2637" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M765.505691 191.942567 639.627772 191.942567c0-35.32453-28.636201-63.960731-63.960731-63.960731L447.74558 127.981836c-35.32453 0-63.960731 28.636201-63.960731 63.960731L257.905908 191.942567c-36.452213 0-66.00325 29.551036-66.00325 66.00325l0 59.875692c0 36.452213 29.551036 66.00325 66.00325 66.00325l-2.042519 0 0 445.681572c0 36.452213 29.551036 66.00325 66.00325 66.00325l61.918211 0 63.960731 0 127.921461 0 63.960731 0 61.918211 0c36.452213 0 66.00325-29.551036 66.00325-66.00325L767.549234 383.823736l-2.042519 0c36.452213 0 66.00325-29.551036 66.00325-66.00325l0-59.875692C831.508941 221.49258 801.958928 191.942567 765.505691 191.942567zM703.58748 803.413046c-0.101307 3.123131-1.743714 27.813462-27.961842 28.134781l-35.998889 0-63.960731 0L447.74558 831.547827 383.78485 831.547827l-35.879162 0c-27.988448-0.343831-27.969005-28.459169-27.969005-28.459169l-0.112564 0.031722L319.824119 383.823736l383.76336 0L703.58748 803.413046zM735.567845 319.863005 287.843754 319.863005c-17.662265 0-31.980365-14.3181-31.980365-31.980365 0-17.662265 14.3181-31.980365 31.980365-31.980365l159.901827 0 127.921461 0 159.901827 0c17.662265 0 31.980365 14.3181 31.980365 31.980365C767.54821 305.544905 753.23011 319.863005 735.567845 319.863005z" p-id="2638"></path><path d="M447.74558 767.588119c17.662265 0 31.980365-14.3181 31.980365-31.980365L479.725946 479.764831c0-17.662265-14.3181-31.980365-31.980365-31.980365-17.662265 0-31.980365 14.3181-31.980365 31.980365l0 255.842922C415.765215 753.270019 430.083316 767.588119 447.74558 767.588119z" p-id="2639"></path><path d="M575.667042 767.588119c17.662265 0 31.980365-14.3181 31.980365-31.980365L607.647407 479.764831c0-17.662265-14.3181-31.980365-31.980365-31.980365-17.662265 0-31.980365 14.3181-31.980365 31.980365l0 255.842922C543.686676 753.270019 558.004777 767.588119 575.667042 767.588119z" p-id="2640"></path></svg>
    </div>
  </div>
</template>

<style>
.van-loading{
  margin-top: 50%;
}
.van-loading .van-loading__text{
  font-size: 18px;
}
.photo-list {
  height: 100vh;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding: 10px;
  box-sizing: border-box;
  background: #f5f5f5;
}

.flex-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding-bottom: env(safe-area-inset-bottom);
}

.flex-item {
  width: calc(25% - 7.5px);  /* 考虑到gap的间距，确保每行4个项目 */
  aspect-ratio: 1;
  overflow: hidden;
  background: #f5f5f5;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: relative;
}

.flex-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.flex-item.need-del::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
}

.item-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #666;
}
.item-box > span {
  font-size: 14px;
  line-height: 16px;
  max-height: 32px;
  overflow: hidden;
  text-align: center;
}

.folder-icon {
  width: 40px;
  height: 40px;
  flex: 0 40px;
}

.video-icon {
  width: 40px;
  height: 40px;
  flex: 0 40px;
  fill: #666;
}

.video-preview {
  width: 100%;
  height: 100%;
  background-color: #aaa;
}

.item-name {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 4px;
  font-size: 12px;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.del-btn{
  position: absolute;
  bottom: 10px;
  left: 10px;
  width: 40px;
  height: 40px;
  border-radius: 20px;
  box-shadow: 0 4px 8px rgba(63, 71, 71, 0.2);
}
.del-btn.true{
  background-color: #f0868f;
}

.del-btn svg{
  width: 24px;
  height: 24px;
  fill: #bbb;
  line-height: 40px;
  margin-left: 8px;
  margin-top: 8px;
}
</style>